<template>
  <div class="login">
    <!-- 
          el-form
          model	表单数据对象	object 
          rules	表单验证规则	object
          validate	对整个表单进行校验的方法，参数为一个回调函数。该回调函数会在校验结束后被调用，并传入两个参数：是否校验成功和未通过校验的字段。若不传入回调函数，则会返回一个 promise	Function(callback: Function(boolean, object))
          el-form-item
          prop	表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的
          el-input
          clearable	是否可清空
          show-password	是否显示切换密码图标
        -->
    <el-form
      :model="login_from"
      :rules="rules"
      label-width="100px"
      class="loginForm"
      ref='loginInfo'
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="login_from.username" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop='password'>
        <el-input v-model="login_from.password" clearable show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="login" type="primary">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入封装好的登录接口
import {userlogin} from '../request/api'
export default {
  data() {
    return {
      login_from: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //封装一个登录事件
    login() {
        this.$refs.loginInfo.validate((val)=>{
            console.log(val,'哈哈哈');
            //val 是验证结果
            if(val){
              console.log(val);
                userlogin(this.login_from)
                .then(res=>{
                  console.log(res,'登录结果');
                  if(res.code==200){
                    console.log(res,'登录结果');
                    this.$message.success(res.msg)
                    //存储到vuex中
                    this.$store.dispatch('changeUserAction',res.list)
                    this.$router.push('/index')
                  }else{
                     this.$message.error(res.msg)
                  }
                })
                .catch(err=>{
                  console.log(err);
                })
            }
        })
    },
  },
};
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  background: #ccc;
}
.loginForm {
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -150px 0 0 -150px;
  width: 400px;
  height: 350px;
}
</style>
